// 全局变量
gameInfo = {
  roomId: null,
  thisUserId: null,
  thatUserId: null,
  isWhite: true,
}

// 界面显示的相关操作

function setScreenText(me) {
  let screen = document.querySelector('#screen');
  console.log(me);
  if (me) {
    screen.innerHTML = "轮到你落子了!";
  } else {
    screen.innerHTML = "轮到对方落子了!";
  }
}

////////////////////////
// 初始化 websocket
//////////////////////
// TODO
let websocket = new WebSocket("ws://127.0.0.1:8080/game");
websocket.onopen = function () {
  console.log("websocket 已连接");
};
websocket.onclose = function () {
  console.log("websocket 已断开");
};
websocket.onerror = function () {
  console.log("websocket 发生错误");
};
websocket.beforeunload = function () {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.close(); // 主动关闭连接
  }
};
window.onbeforeunload = function () {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.close(); // 主动关闭连接
    console.log('主动关闭连接');
  }
};
window.onbeforeunload = function (e) {
  return '刷新页面将导致您退出游戏房间，是否确认刷新？';
};

websocket.onmessage = function (event) {
  console.log('[handlerGameMessage]' + event.data);
  let resp = JSON.parse(event.data);

  if (!resp.ok) {
    alert("游戏连接失败! reason:" + resp.reason);
    location.href = 'game_hall.html';
    return;
  }

  if (resp.message == 'gameReady') {
    gameInfo.roomId = resp.roomId;
    gameInfo.thisUserId = resp.thisUserId;
    gameInfo.thatUserId = resp.thatUserId;
    gameInfo.isWhite = (resp.isWhite == resp.thisUserId);
    console.log(gameInfo.thisUserId);
    console.log(gameInfo.thatUserId);
    console.log(gameInfo.isWhite);

    // 初始化棋盘
    initGame();

    //显式对手名称
    document.getElementById("opponent-name").innerText = "对手：" + resp.thatUserName;
    console.log("对手名字已设置成功" + event.data.thatUserName)

    // 设置显示区域的内容
    setScreenText(gameInfo.isWhite);
  }

  if (resp.message != 'gameReady' && resp.message != 'RepeatConnection') {
    console.log("响应异常!");
    return;
  }

  if (resp.message == 'RepeatConnection') {
    console.log("请勿重复连接进入游戏房间!");
    location.href = 'game_hall.html';
  }


};

// 初始化一局游戏
function initGame() {
  // 是我下还是对方下. 根据服务器分配的先后手情况决定
  let me = gameInfo.isWhite;
  // 游戏是否结束
  let over = false;
  let chessBoard = [];
  //初始化chessBord数组(表示棋盘的数组)
  for (let i = 0; i < 15; i++) {
    chessBoard[i] = [];
    for (let j = 0; j < 15; j++) {
      chessBoard[i][j] = 0;
    }
  }
  let chess = document.querySelector('#chess');
  let context = chess.getContext('2d');
  context.strokeStyle = "#BFBFBF";
  // 背景图片
  let logo = new Image();
  logo.src = "/image/bg.png";
  logo.onload = function () {
    context.drawImage(logo, 0, 0, 450, 450);
    initChessBoard();
  }

  // 绘制棋盘网格
  function initChessBoard() {
    for (let i = 0; i < 15; i++) {
      context.moveTo(15 + i * 30, 15);
      context.lineTo(15 + i * 30, 430);
      context.stroke();
      context.moveTo(15, 15 + i * 30);
      context.lineTo(435, 15 + i * 30);
      context.stroke();
    }
  }

  // 绘制一个棋子, me 为 true
  function oneStep(i, j, isWhite) {
    context.beginPath();
    context.arc(15 + i * 30, 15 + j * 30, 13, 0, 2 * Math.PI);
    context.closePath();
    var gradient = context.createRadialGradient(15 + i * 30 + 2, 15 + j * 30 - 2, 13, 15 + i * 30 + 2, 15 + j * 30 - 2, 0);
    if (!isWhite) {
      gradient.addColorStop(0, "#0A0A0A");
      gradient.addColorStop(1, "#636766");
    } else {
      gradient.addColorStop(0, "#D1D1D1");
      gradient.addColorStop(1, "#F9F9F9");
    }
    context.fillStyle = gradient;
    context.fill();
  }

  chess.onclick = function (e) {
    if (over) {
      return;
    }
    if (!me) {
      return;
    }
    let x = e.offsetX;
    let y = e.offsetY;
    // 注意, 横坐标是列, 纵坐标是行
    let col = Math.floor(x / 30);
    let row = Math.floor(y / 30);
    if (chessBoard[row][col] == 0) {
      // TODO 发送坐标给服务器, 服务器要返回结果
      send(row, col);
      oneStep(col, row, gameInfo.isWhite);
      chessBoard[row][col] = 1;
    }
  }

  function send(row, col) {
    let req = {
      message: 'putChess',
      userId: gameInfo.thisUserId,
      row: row,
      col: col
    };
    websocket.send(JSON.stringify(req));

  }

  //之前websocket.onmessage方法主要用来处理游戏就绪响应 
  // 但现在游戏就绪后就需要在initGame内部中修改为处理落子响应
  websocket.onmessage = function (event) {
    //打印日志
    console.log('[handlerGameMessage]' + event.data);
    //处理响应数据
    let resp = JSON.parse(event.data);
    //判断返回类型
    if (resp.message != 'putChess') {
      console.log("响应异常!");
      return;
    }
    //判断谁下的子
    if (resp.userId == gameInfo.thisUserId) {
      //我自己落的子
      //根据颜色来绘制棋子
      oneStep(resp.col, resp.row, gameInfo.isWhite);

    } else if (resp.userId == gameInfo.thatUserId) {
      //对方下的子
      oneStep(resp.col, resp.row, !gameInfo.isWhite);
    }

    chessBoard[resp.row][resp.col] = 1;
    //交换轮次
    me = !me;
    setScreenText(me);

    //判断游戏是否结束
    let screenDiv = document.querySelector('#screen');
    if (resp.winner != 0) {
      if (resp.winner == gameInfo.thisUserId) {
        // alert("恭喜你,你赢了!");
        screenDiv.innerHTML = "恭喜你,你赢了!";
      } else if (resp.winner == gameInfo.thatUserId) {
        // alert("很遗憾,你输了!");
        screenDiv.innerHTML = "很遗憾,你输了!";
      } else {
        alert("winner字段错误!");
      }
      // location.href = '/game_hall.html';
      //新增一个按钮点击后跳转到游戏大厅
      let backBtn = document.createElement('button');
      backBtn.innerHTML = '返回游戏大厅';
      backBtn.onclick = function () {
        location.href = 'game_hall.html';
      }
      let fatherDiv = document.querySelector('.container>div');
      fatherDiv.appendChild(backBtn);
    }

  }
}
